// 操作localstorage

class DataHelper {
  dataKey!: string; // key
  primaryKey!: string;

  constructor(dataKey: string, primaryKey: string) {
    this.dataKey = dataKey
    this.primaryKey = primaryKey
  }

  // 读取操作
  readData():any {
    // 根据键值去读取数据，可能有可能没有
    let strData: string | null = localStorage.getItem(this.dataKey)
    // 读取到的数组
    let arrData:any = []
    if(strData != null) {
      arrData = JSON.parse(strData)
    }
  }

  // 保存到localstorage
  saveData(arrData: Array<object>):void {
    let str:string = JSON.stringify(arrData)
    localStorage.setItem(this.dataKey, str)
  }

  // 添加操作 ,-- 把要添加的对象传进去，添加成功之后返回当前的id
  addData(newDataObj: any): number {
    // 先读取localstorage中的数组，有的话追加，没有的话新建数组
    let dataArray = this.readData()
    if(dataArray == null) {
      dataArray = []
    }
    let newId = dataArray.length > 0 ? dataArray[dataArray.length -1][this.primaryKey]+1 : 1
    newDataObj[this.primaryKey] = newId
    dataArray.push(newDataObj)
    // 保存在localstorage中
    this.saveData(dataArray)

    return newId
  }

  // 删除操作，-- 根据id值删除
  removeDataById(id: number | string):boolean {
    let arr = this.readData()
    let index = arr.findIndex((ele: any) => {
      return ele[this.primaryKey] == id
    })
    if(index > -1) {
      arr.splice(index, 1)
      this.saveData(arr)
      return true
    } else {
      return false
    }
  }
}

export default DataHelper;